#include "video_stream.h"
#include "common.h"

void PushVideoFrame(mk_media media, const char* data, int size, uint64_t pts) {
    int cam_id = -1;
    for (int i = 0; i < MAX_CAMERAS; i++) {
        if (g_media[i] == media) {
            cam_id = i;
            break;
        }
    }
    if (cam_id == -1) {
        fprintf(stderr, "Error: Unknown media handle, cannot push video frame.\n");
        return;
    }

    StreamState* state = &g_stream_states[cam_id];
    pthread_mutex_lock(&state->mutex);

    if (!state->video_inited) {
        codec_args v_args = {0};
        v_args.video.width = 1920;
        v_args.video.height = 1080;
        v_args.video.fps = 15;

        mk_track v_track = mk_track_create(MKCodecH264, &v_args);
        if (v_track) {
            mk_media_init_track(media, v_track);
            mk_track_unref(v_track);
            state->video_inited = 1;
            printf("📹 Thread %d: H.264 track initialized.\n", cam_id);
        }
    }

    if (!state->init_completed && state->video_inited && state->audio_inited) {
        mk_media_init_complete(media);
        state->init_completed = 1;
        printf("✅ Media init complete for cam %d\n", cam_id);
    }

    pthread_mutex_unlock(&state->mutex);

    mk_frame frame = mk_frame_create(MKCodecH264, pts, pts, data, size, NULL, NULL);
    if (frame) {
        mk_media_input_frame(media, frame);
        mk_frame_unref(frame);
    }
}

void* pull_video_stream_thread(void* arg) {
    CameraStream* camera = (CameraStream*)arg;
    AVFormatContext *fmt_ctx = NULL;
    int video_stream_index = -1;
    AVPacket pkt;

    printf("📹 Thread %d: Starting to pull video stream from %s\n", 
           camera->cam_id, camera->input_stream);

    while (1) {
        // 打开输入流
        if (avformat_open_input(&fmt_ctx, camera->input_stream, NULL, NULL) < 0) {
            fprintf(stderr, "Thread %d: Failed to open input stream, retrying...\n", camera->cam_id);
            usleep(1000000);
            continue;
        }

        // 查找流信息
        if (avformat_find_stream_info(fmt_ctx, NULL) < 0) {
            fprintf(stderr, "Thread %d: Failed to find stream info\n", camera->cam_id);
            avformat_close_input(&fmt_ctx);
            usleep(1000000);
            continue;
        }

        // 查找视频流
        for (int i = 0; i < fmt_ctx->nb_streams; i++) {
            AVCodecParameters *codecpar = fmt_ctx->streams[i]->codecpar;
            if (codecpar->codec_type == AVMEDIA_TYPE_VIDEO && video_stream_index == -1) {
                video_stream_index = i;
                printf("📹 Thread %d: Video stream found (index %d, codec: %d)\n", 
                       camera->cam_id, i, codecpar->codec_id);
                break;
            }
        }

        if (video_stream_index == -1) {
            fprintf(stderr, "Thread %d: No video stream found.\n", camera->cam_id);
            avformat_close_input(&fmt_ctx);
            usleep(1000000);
            continue;
        }

        // 读取并推送视频帧
        while (av_read_frame(fmt_ctx, &pkt) >= 0) {
            if (pkt.stream_index == video_stream_index) {
                uint64_t pts_ms = (uint64_t)((pkt.pts == AV_NOPTS_VALUE ? 0 : 
                    av_q2d(fmt_ctx->streams[pkt.stream_index]->time_base) * pkt.pts) * 1000);
                PushVideoFrame(g_media[camera->cam_id], (const char*)pkt.data, pkt.size, pts_ms);
            }
            av_packet_unref(&pkt);
        }

        avformat_close_input(&fmt_ctx);
        video_stream_index = -1;
        usleep(500000);
    }

    free(camera);
    return NULL;
}

